<template>
  <div class="page login">
    <div class="header_register">
			<div class="register">
				<a href="#" style="float: right;">注册</a>
			</div>
		</div>
		<div class="header">
			<img src="http://fresh.huruqing.cn/img/logo.adec77d3.png" >
		</div>
		<form class="fresh_content">
			<p class="tel_content">
				<input type="text" name="17620758225" class="tel" placeholder="请输入手机号" v-model="phone"/>
				<button type="button" @click="getCode">{{msg}}</button>
			</p>
			<p class="code_content">
				<input type="text" name="8848" class="code" placeholder="请输入验证码" v-model="smsCode"/>
			</p>
			<a><button type="button" class="to_login" @click="login">短信登录</button></a>
		</form>
  </div>
</template>

<script>
export default {
  data(){
    return {
      // 获取验证码的按钮文字
      msg: '获取验证码',
      phone: '13800000000',
      smsCode: '',
      count: 5,
      // 是否正在获取验证码
      gettting: false
    }
  },

  methods: {
    async getCode() {
      // 如果getting为true,说明正则获取验证码, 不允许继续执行
      if (this.gettting) return false;
      try {
        // 点击按钮, 设置为true
        this.gettting = true;
        let timer = setInterval(() => {
            this.msg = this.count--;
            if (this.count ===0) {
              clearInterval(timer);
              this.msg = '重新获取验证码';
              // gettting设置为false, 可以重新点击
              this.gettting = false;
            }
        }, 1000);

        let res = await this.$axios.get('/user/getSmsCode',{phone: this.phone}) 
        this.smsCode = res.smsCode;
      } catch (error) {
        console.log(error);
      }
    },

    async login() {
      try {
        let data = {phone: this.phone,smsCode: this.smsCode};
        let res  = await this.$axios.post('/user/login',data)
        // 更新phone,token,isLogin
        this.$store.commit('updateLoginState',true);
        this.$store.commit('updatePhone',this.phone);
        this.$store.commit('updateToken',res.result.token);
        this.$router.go(-1);
      } catch (error) {
        console.log(error);
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import './login.less';
.page {background: #fff;}
</style>